package com.example.demo_news.service.User;

import java.util.ArrayList;
import java.util.List;

import com.example.demo_news.Repository.NewsRepository;
import com.example.demo_news.Repository.OfficialRepository;
import com.example.demo_news.Repository.SubscribeRepository;
import com.example.demo_news.entity.MyUser;
import com.example.demo_news.entity.News;
import com.example.demo_news.entity.OfficialAccount;
import com.example.demo_news.entity.Subscribe;
import com.example.demo_news.until.UserUntil;
import com.fasterxml.jackson.annotation.JsonCreator.Mode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Service
public class UserIndexService {
    @Autowired 
    private UserUntil userUntil;
    @Autowired
    private OfficialRepository officialRepository;
    @Autowired
    private SubscribeRepository subscribeRepository;
    //根据用户的关注和用户的Id返回推送的新闻
    @Autowired
    private NewsRepository newsRepository;
    public List<News> findNewsByUserId(){
        MyUser user=userUntil.getUser();
          return null;
    }
    //返回所有的新闻号
    public List<OfficialAccount> findAll(){
        return officialRepository.findAll();
    }
    //返回关注的新闻号
    public List<OfficialAccount>findLikeOfficialAccount(){
        MyUser user=userUntil.getUser();
        List<Subscribe> subscribes=subscribeRepository.findByPersonId(user.getPerson().getId());
        List<OfficialAccount>officialAccounts=new ArrayList<>();
        for(Subscribe subscribe:subscribes){
            officialAccounts.add(officialRepository.findOfficialAccountById(subscribe.getOfficialAccountId()));
        }
        return officialAccounts;
    }
  //添加关注
    public boolean likeService(Integer id){
        MyUser user=userUntil.getUser();
        Subscribe subscribe=new Subscribe();
        subscribe.setOfficialAccountId(id);
        subscribe.setPersonId(user.getPerson().getId());
        //查看数据库中是否有此条记录
        if(subscribeRepository.findSubscribeByPersonIdAndOfficialAccountId(user.getPerson().getId(), id).getId()==null){
           subscribeRepository.save(subscribe);
        }
        return true;
    }
    //返回订阅的新闻
    public boolean subscribeNews(Model model){
        MyUser user=userUntil.getUser();
        //获取当前登陆的账号
        //查询出我关注的新闻号
        List<Subscribe>subscribes=subscribeRepository.findByPersonId(user.getPerson().getId());
        //然后找出每个新闻号发布的新闻
        List<News>newsList=new ArrayList<>();
        for(Subscribe subscribe:subscribes){
            newsList.addAll(newsRepository.findNewsByofficialAccountId(subscribe.getOfficialAccountId()));
        }
        model.addAttribute("newsList", newsList);
        return true;
    }
    //返回所有新闻
    public boolean findAllNews(Model model){
        List<News>newsList=newsRepository.findAll();
        model.addAttribute("newsList", newsList);
        return true;
    }
}
